package com.sample.springbatch.scheduling.service;

import com.sample.springbatch.job.service.BatchJobService;
import com.sample.springbatch.scheduling.model.QuartzJobInfo;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.core.converter.DefaultJobParametersConverter;
import org.springframework.batch.core.converter.JobParametersConverter;
import org.springframework.batch.support.PropertiesConverter;

import java.util.Date;

/**
 * 任务执行类  根据任务名称执行相应的批量任务
 * Created by zwg on 2016/6/18.
 */

public class BatchJobFactory implements Job {
    public static final Logger logger = LoggerFactory.getLogger(BatchJobFactory.class);
    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        QuartzJobInfo jobExtInfo = (QuartzJobInfo)jobExecutionContext.getMergedJobDataMap().get("jobInfo");
        BatchJobService jobService = (BatchJobService)jobExecutionContext.getMergedJobDataMap().get("jobService");

        String params = "sys_time:"+new Date().toString();
        JobParametersConverter jobParametersConverter = new DefaultJobParametersConverter();
        JobParameters jobParameters = jobParametersConverter.getJobParameters(PropertiesConverter.stringToProperties(params));

        try {
            jobService.launch(jobExtInfo.getName(),jobParameters,true);
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
    }
}
